package com.mercury.rabbitmq.config.business;


import com.mercury.rabbitmq.config.dead.DeadBuilder;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 业务队列绑定关系
 *
 * @author mercury
 */
@Configuration
@ConditionalOnProperty(
        name = {"spring.rabbitmq.enabled"},
        havingValue = "true"
)
public class BusinessQueueConfig {



    /**
     * 业务queue (将业务队列和死信交换机绑定)
     *
     * @return 队列
     */
    @Bean
    public Queue businessQueue() {
        Map<String, Object> args = new HashMap<>(2);
        // x-dead-letter-exchange    这里声明当前队列绑定的死信交换机
        args.put("x-dead-letter-exchange", DeadBuilder.DEAD_LETTER_EXCHANGE);
        // x-dead-letter-routing-key  这里声明当前队列的死信路由key
        args.put("x-dead-letter-routing-key", DeadBuilder.DEAD_LETTER_QUEUE_ROUTING_KEY);
        return QueueBuilder.durable(BusinessBuilder.BUSINESS_QUEUE_NAME).withArguments(args).build();
    }



    /**
     * 声明业务交换机
     *
     * @return 业务交换机
     */
    @Bean
    public DirectExchange businessExchange() {
        return new DirectExchange(BusinessBuilder.BUSINESS_EXCHANGE);
    }


    /**
     * 绑定业务队列和业务交换机
     *
     * @param queue    队列
     * @param exchange 交换机
     * @return 绑定
     */
    @Bean
    public Binding businessBinding(@Qualifier("businessQueue") Queue queue,
                                    @Qualifier("businessExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(BusinessBuilder.BUSINESS_QUEUE_ROUTING_KEY);
    }

}
